You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Reduce memory used to save conversation history - #2722
Long conversation histories can exhaust the extension host heap during a save.
Copy arrays and plain objects without copying their string values. Track object identity and preserve sparse arrays. If the graph contains a special object, use the native clone for the full graph so references across that boundary stay intact. Leave locking, save order, and retry behavior in place.
Test Procedure
Use a task with a large UI and API transcript. Save repeatedly while the task receives new messages. An allocation capture showed 120 MB of UI history and 156 MB of API history in one affected task.
The checks below ran in the Linux review container with Node and pnpm.
This patch can be reviewed on its own. Assignment is pending. The author reviewed the local changes. AI assistance was used for implementation, tests, and preparation of this draft. Maintainers can reach @cartridgebasic in this thread.
Share immutable strings while copying mutable transcript containers. Use a native clone for the full graph when a legacy value needs it.
Refs Zoo-Code-Org#2721
No actionable comments were generated in the recent review.
Summary
Summary by CodeRabbit
Bug Fixes
Task and API histories now retain independent snapshots when saves happen concurrently, preventing later changes from altering previously saved records.
Retries capture the latest task data without changing snapshots from earlier failed attempts, helping preserve accurate history for nested inputs and related data.
Snapshot handling now better preserves relationships and special values in task history, reducing the risk of saved records differing from the data at the time of saving.
Adds snapshotHistory to copy plain history graphs while preserving cycles and shared references. Unsupported values use a whole-graph structuredClone fallback. UI and API persistence paths now use this function before saving.
Changes: Task History Snapshots
Layer / File(s)
Summary
Snapshot history graphs src/core/task-persistence/historySnapshot.ts, src/core/task-persistence/__tests__/historySnapshot.spec.ts
Adds graph copying for arrays and plain or null-prototype objects, preserving cycles and shared references. Unsupported values trigger a whole-graph structuredClone fallback. Tests cover graph shape, special objects, accessors, and errors.
Use snapshots for persistence src/core/task/Task.ts, src/core/task/__tests__/Task.persistence.spec.ts
UI and API history save paths use snapshotHistory instead of structuredClone. Tests cover independent save snapshots, failed-save retries, and updated nested input on API retry.
This change reduces memory use when saving large conversation histories while keeping save behavior the same. No merge-blocking risk was identified.
Pre-merge checks: 8
Check name
Status
Explanation
Title check
The title names the main change: reducing memory used when saving conversation history. The PR adds a snapshot function that copies arrays and plain objects, and Task.ts uses it in the UI and API save…
Description check
The description follows the template. It links the issue (Closes #2721) and explains the approach, including identity tracking, sparse arrays, and the native clone fallback. It gives a concrete test p…
Linked Issues check
[#2721] Requirement: stop large per-save allocations in Task.saveClineMessages() and Task.saveApiConversationHistory() so that saves keep the full conversation without heap exhaustion. At head 7f1bfef…
Out of Scope Changes check
All changes relate to #2721. historySnapshot.ts holds the snapshot logic. Task.ts changes only the persistence call sites to use snapshotHistory(). historySnapshot.spec.ts and Task.persistence.spec.ts…
Regression Evidence
The changed behavior is the new snapshotHistory helper (src/core/task-persistence/historySnapshot.ts) and its use in Task.saveApiConversationHistory and Task.saveClineMessages. No visible UI c…
Security Boundaries
The PR changes four files: a new src/core/task-persistence/historySnapshot.ts, two replaced structuredClone calls in src/core/task/Task.ts, and two test files. I read the full diff for the chang…
Persistence Integrity
The PR changes two persistence paths in src/core/task/Task.ts. saveApiConversationHistory and saveClineMessages now pass snapshotHistory(...) instead of structuredClone(...) to `saveApiMessage…
Lifecycle Resource Cleanup
The changed lifecycle paths do not introduce a listener, watcher, provider, timer, task, or other resource leak, and they do not add duplicate work after cancellation, disposal, or restart. Diff evide…
Full details: Title check
Explanation
The title names the main change: reducing memory used when saving conversation history. The PR adds a snapshot function that copies arrays and plain objects, and Task.ts uses it in the UI and API save paths. The title is short, specific, and in active voice. It does not use file lists or vague terms.
Full details: Description check
Explanation
The description follows the template. It links the issue (Closes #2721) and explains the approach, including identity tracking, sparse arrays, and the native clone fallback. It gives a concrete test procedure with commands and results, and it marks the checklist and documentation sections. Some items remain incomplete. The Issue Linked checkbox is unchecked, although the description links the issue. The Recorded Stream section is left blank, but it applies only to new provider PRs. The Get in Touch section still has the placeholder comment and no Discord name. The Description section does not describe the trade-offs or the reviewer checks that the template asks for. The Additional Notes say the patch can be reviewed alone and that assignment is pending, which adds little to the review. The Visual Snapshots and Videos sections are omitted, which is acceptable for a non-UI change.
Resolution
Optional improvements: tick the Issue Linked checkbox, add a Discord name or remove the placeholder comment in Get in Touch, and state the trade-offs and the parts reviewers should check closely, such as the fallback to structuredClone for special objects.
Full details: Linked Issues check
Explanation
[#2721] Requirement: stop large per-save allocations in Task.saveClineMessages() and Task.saveApiConversationHistory() so that saves keep the full conversation without heap exhaustion. At head 7f1bfef, src/core/task-persistence/historySnapshot.ts still implements snapshotHistory(). It rebuilds arrays and plain or null-prototype objects, returns string and other primitive values as-is, tracks identity through a WeakMap so aliases and cycles are preserved, and keeps sparse arrays and extra array properties. Functions, symbols, proxies, non-plain prototypes, and accessors throw a private sentinel. The helper then runs structuredClone on the whole graph, so cross-boundary references stay intact. The spec file at head covers these cases: no structuredClone call for ordinary data, aliases and cycles, holes and extra properties, own proto with normal and null prototypes, whole-graph fallback with Map, Set, Date, ArrayBuffer and view references, single getter evaluation, and DataCloneError for function, symbol, and proxy inputs. The incremental change since the previous review strengthens these tests. It does not alter the core snapshot logic shown at head. Limits: the incremental diff could not be read, so the exact test edits are known only from the PR objectives and the spec file at head. The PR does not report the result of a repeated-save heap measurement, so the heap reduction is not measured. These gaps do not block a coding-requirement PASS.
Full details: Out of Scope Changes check
Explanation
All changes relate to #2721. historySnapshot.ts holds the snapshot logic. Task.ts changes only the persistence call sites to use snapshotHistory(). historySnapshot.spec.ts and Task.persistence.spec.ts test the snapshot helper and persistence behavior. The incremental change strengthens regression tests, which supports the same objective. The PR states that locking, save order, and retry behavior are unchanged. No unrelated change is evident in the inspected files. The incremental diff could not be read, so this verdict rests on the whole-PR summary and the spec and source files at head.
Full details: Regression Evidence
Explanation
The changed behavior is the new snapshotHistory helper (src/core/task-persistence/historySnapshot.ts) and its use in Task.saveApiConversationHistory and Task.saveClineMessages. No visible UI changes are in the diff, so snapshot requirements do not apply. Test evidence at the lowest valid layer: - historySnapshot.spec.ts is a unit spec that calls the real snapshotHistory function. It does not copy the implementation. It covers: - the ordinary plain-container path, including a check that structuredClone is not called; - aliases and cycles; - array holes, explicit undefined, extra array properties, and primitives such as NaN, BigInt, and -0; - own __proto__ properties under both normal and null prototypes; - whole-graph fallback for Map, Set, Date, ArrayBuffer, and typed-array graphs; - accessors, with a check that the getter runs once; - the negative and error cases: DataCloneError for functions, symbols, and proxies. - Task.persistence.spec.ts covers the changed call sites through the real save methods. It checks isolation across concurrent saves, fresh snapshots on retry without mutating the failed snapshot, reference preservation across legacy special objects, and API backoff with nested tool input. I did not find a concrete, plausible regression case that lacks a test. A possible gap is a direct test for a custom class instance, which the code rejects through the prototype check. That path shares the fallback branch that the Map/Set/Date graph test already covers, so I do not treat it as a concrete gap.
Full details: Security Boundaries
Explanation
The PR changes four files: a new src/core/task-persistence/historySnapshot.ts, two replaced structuredClone calls in src/core/task/Task.ts, and two test files. I read the full diff for the changed paths. - Task.ts changes only two lines. saveApiConversationHistory and saveClineMessages now call snapshotHistory(...) instead of structuredClone(...). The lock, save order, retry logic, and the saveApiMessages/saveTaskMessages destinations are unchanged. No approval, allowlist, or command-execution path is touched. - historySnapshot.ts rebuilds arrays and plain or null-prototype objects. It copies only own enumerable string-keyed data properties, using Object.defineProperty. This avoids invoking __proto__ setters. Accessors, functions, symbols, proxies, and non-plain prototypes fall back to structuredClone. The data is the task's own conversation history, which the existing code already persisted. The change does not add a new input source, does not evaluate input, and does not expose secrets or personal data beyond what the previous structuredClone path already wrote to the same storage. I found no concrete defect in a changed path that matches the check's criteria (exposed secrets or personal data, trusted or executed unvalidated input, or bypassed approval/allowlist controls). Behavior differences such as deep-recursion limits or dropped non-enumerable properties affect correctness, not the security boundaries named in this check.
Full details: Persistence Integrity
Explanation
The PR changes two persistence paths in src/core/task/Task.ts. saveApiConversationHistory and saveClineMessages now pass snapshotHistory(...) instead of structuredClone(...) to saveApiMessages and saveTaskMessages. The diff touches nothing else in those methods. The await, the merge flag, the task ID, and the storage path are unchanged, so write ordering and retry behavior stay as they were. I read the new snapshotHistory in src/core/task-persistence/historySnapshot.ts and checked each condition that could lose or corrupt state: - Snapshot isolation: arrays and plain or null-prototype objects are rebuilt. Strings and other primitives are returned as-is, which is safe because they are immutable. - Aliases and cycles: a WeakMap keeps the copy identical to the source graph. - Sparse arrays: new Array(length) plus copying only own keys keeps the holes. - Own __proto__ keys: Object.defineProperty stores them as data properties. - Accessors, functions, symbols, proxies, and other prototypes (Map, Set, Date, typed arrays, class instances): these throw the internal sentinel, and the whole graph goes to structuredClone. That keeps the old semantics, including DataCloneError for functions and symbols. - Partial failure: the plain-copy pass has no side effects on the source and writes nothing to storage. Its partial result is discarded before the fallback runs. I found no write without await, no non-atomic write, and no missing rollback path in the changed code. The change does not alter the persistence write logic itself. Its risk is memory use, which the check does not cover.
Full details: Lifecycle Resource Cleanup
Explanation
The changed lifecycle paths do not introduce a listener, watcher, provider, timer, task, or other resource leak, and they do not add duplicate work after cancellation, disposal, or restart. Diff evidence (base..head): - src/core/task-persistence/historySnapshot.ts (new file) adds snapshotHistory<T>. It is synchronous. It creates no listeners, timers, watchers, or providers. Its only state is a local WeakMap and a local snapshot tree, both released when the call returns. On a fallback, the partial snapshot is left for garbage collection. It does not hold a resource. - src/core/task/Task.ts: the only changes replace structuredClone(this.apiConversationHistory) in saveApiConversationHistory and structuredClone(this.clineMessages) in saveClineMessages with snapshotHistory(...). The call sites, await flow, merge flag, and surrounding try/catch are unchanged. The contributor states that locking, save order, and retry behavior are unchanged, and the diff does not contradict this. - The two spec files are test-only additions. They do not change runtime lifecycle code. No changed path adds a cleanup obligation or a repeated operation on cancel, dispose, or restart. The change does not alter when saves run or how often they retry.
Finishing Touches
Generate unit tests (beta)
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 2 remain after this review.
Recent review details
Context from checks skipped due to timeout: 2
GitHub Check: CodeRabbit
GitHub Check: extension-host-visual
Additional context used
Path-based instructions: 5
Check saved state and lifecycle rules.
CodeRabbit configuration file
Files:
src/core/task/Task.ts
Require regression tests at the lowest test layer that can show the behavior.
Thanks for contributing. This comment tracks the review sequence and the next action.
Current step: Awaiting fresh human maintainer or CODEOWNER approval.
Automated review is complete for the latest commit but does not replace human approval.
Review-state labels are managed by this workflow; do not edit them manually. community-approved is managed the same way — do not add or remove it manually. It signals a fresh community code approval for the current head as an advisory priority only; maintainer review is still required.
The workflow uploads generated reports in the changed-code-mutation-report artifact. A direct artifact link appears below after upload.
Advisory findings
extension Stryker preflight failed: 19:28:03 (2931) INFO ProjectReader Found 2 of 1453 file(s) to be mutated. 19:28:03 (2931) INFO Instrumenter Instrumented 2 source file(s) with 52 mutant(s) 19:28:03 (2931) INFO ConcurrencyTokenProvider Creating 2 test runner process(es). 19:28:05 (2931) INFO DryRunExecutor Note: running the dry-run only. No mutations will be tested. 19:28:05 (2931) INFO DryRunExecutor Starting initial test run (vitest test runner with "perTest" coverage analysis). This may take a while. 19:30:44 (2931) ERROR DryRunExecutor One or more tests failed in the initial test run: coding eval host command boundary rejects an outside-workspace git diff in clamp-range before command execution Cannot find module '../../../../scripts/agent-evals/coding-fixtures' imported from /home/runner/work/Zoo-Code/Zoo-Code/.stryker-tmp/sandbox-wHuT4C/core/tools/__tests__/coding-eval-boundary.spec.ts 19:30:44 (2931) ERROR Stryker There were failed tests in the initial test run. file:///home/runner/work/Zoo-Code/Zoo-Code/node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@stryker-mutator/core/dist/src/process/3-dry-run-executor.js:65 throw new ConfigError('There were failed tests in the initial test run.'); ^ ConfigError: There were failed tests in the initial test run. at DryRunExecutor.validateResultCompleted (file:///home/runner/work/Zoo-Code/Zoo-Code/node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@stryker-mutator/core/dist/src/process/3-dry-run-executor.js:65:27) at DryRunExecutor.executeDryRun (file:///home/runner/work/Zoo-Code/Zoo-Code/node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@stryker-mutator/core/dist/src/process/3-dry-run-executor.js:100:14) at process.processTicksAndRejections (node:internal/process/task_queues:103:5) at async WorkItem.execute (file:///home/runner/work/Zoo-Code/Zoo-Code/node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@stryker-mutator/core/dist/src/concurrent/pool.js:32:28) at async file:///home/runner/work/Zoo-Code/Zoo-Code/node_modules/.pnpm/@[email protected]_@[email protected]/node_modules/@stryker-mutator/core/dist/src/concurrent/pool.js:69:13 { innerError: undefined } Node.js v22.23.4
The reason will be displayed to describe this comment to others. Learn more.
These cases only assert .toThrow(). Would they still pass if the internal sentinel Symbol leaked out of snapshotHistory? Could we assert expect.objectContaining({ name: "DataCloneError" }) and add %s to the title so each case has its own name?
The reason will be displayed to describe this comment to others. Learn more.
setPrototypeOf(original, null) makes this a null-prototype case. A plain snapshot[key] = copy(...) would still pass here, because a null-prototype object has no __proto__ setter. Could we add a case with a normal-prototype object from JSON.parse('{"__proto__":...}')?
Thanks for running the benchmark. Both test changes make sense. I’ll give each failure case its own name and check for DataCloneError explicitly so a leaked internal Symbol fails the test. I’ll also add a JSON.parse case where a regular object has its own __proto__ property. I’ll re-request your review once both changes are in.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Reduce memory used to save conversation history
Related GitHub Issue
Closes #2721
Description
Long conversation histories can exhaust the extension host heap during a save.
Copy arrays and plain objects without copying their string values. Track object identity and preserve sparse arrays. If the graph contains a special object, use the native clone for the full graph so references across that boundary stay intact. Leave locking, save order, and retry behavior in place.
Test Procedure
Use a task with a large UI and API transcript. Save repeatedly while the task receives new messages. An allocation capture showed 120 MB of UI history and 156 MB of API history in one affected task.
The checks below ran in the Linux review container with Node and pnpm.
All listed checks passed.
Pre-Submission Checklist
Documentation Updates
Additional Notes
This patch can be reviewed on its own. Assignment is pending. The author reviewed the local changes. AI assistance was used for implementation, tests, and preparation of this draft. Maintainers can reach @cartridgebasic in this thread.
Get in Touch